<?php

namespace App\Listeners;

use App\Events\Event;
use App\Events\AccountEvent;



class AccountListener extends Listener
{

    /**
     * @param AccountEvent $event
     */
    public function handle(AccountEvent $event)
    {
        switch($event->action)
        {
            case Event::CHECK:
                $this->check($event); break;
            case Event::RESET:
                $this->reset($event); break;
            default: break;
        }
    }


    protected function check(AccountEvent $event)
    {
        try{
            $org = Event::getOrg();
            $password = $org['registerDefaultPwd'];
            $this->setUri('modifyPassword');
            $data = $this->dataMaker();
            $data["telephone"] = $event->account;
            $data["oldMd5pass"] = md5($password);
            $data["md5pass"] = md5($password);
            $this->setRequest($data);
            $result = $this->callEeoApi();

            $code = $result['error_info']['errno'];
            if($code == 113){
                throw new \Exception('OK', 113);
            }
            if(!in_array($code,[1,137,138])){
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }

    }

    protected  function  reset(AccountEvent $event)
    {
        try{
            $this->setUri('modifyPasswordByTelephone');
            $data = $this->dataMaker();
            $data["telephone"] = $event->account;
            $data["md5pass"] = md5($event->password);
            $this->setRequest($data);
            $result = $this->callEeoApi();

            if($result['error_info']['errno'] <> 1){
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }


}
